<?php

defined('IN_MY_PHP') || die(0);


/**
 *  配置文件，内容如下
 * return [
 *   'jfzt'=>[
 *      // 方式一（推荐）
 *      ['val'=>0, 'label'=>'xxx0', 'style'=>'txt-danger'],
 *      ['val'=>1, 'label'=>'xxx1', 'style'=>'txt-success'],
 *      // 方式二（简化，不支持样式）
 *      0=>xxx0,
 *      1=>xxx1,
 *      ...
 *   ],
 * ];
 * @author netmou <leiyanfo@sina.com>
 */
class Config
{
	private static $container = array();
	
	/** 加载配置 */
	public static function load($name, $path = null)
	{
		if (!isset(self::$container[$name])) {
			$fileName = $name.'.cfg.php';
			if ($path == null) {
				$path = dirname($_SERVER['SCRIPT_FILENAME']);
			}
			
			$file = rtrim(preg_replace('/[\\\\\\/]/', DS, $path), DS) . DS . $fileName;
			if (file_exists($file) && is_readable($file)) {
				self::$container[$name] = include $file; // the method must be include
				if(!is_array(self::$container[$name])){
					trigger_error('配置文件错误！', E_USER_ERROR);
				}
			}else{
				trigger_error("配置文件:'{$file}' 未找到.", E_USER_ERROR);
			}
			
		}

		return self::$container[$name];
	}
	/** 获取标签 */
	public static function getLabel($name, $val, $style = false, $mod = null){
		if($mod == null){
			$mod = basename(dirname($_SERVER['SCRIPT_FILENAME']));
		}
		$context = self::load($mod, null);
	
		if($context[$name] == null){
			trigger_error('未找到配置项！', E_USER_ERROR);
		}
		if(is_array($val)){
			$val = $val[$name];
		}
		foreach($context[$name] as $cVal => &$cLabel){
			if(is_scalar($cLabel) && $cVal == $val){
				return $cLabel;
			}
			if(is_array($cLabel) && $cLabel['val'] == $val){
				return ($style == false)?$cLabel['label']:'<span class="'.$cLabel['style'].'">'.$cLabel['label'].'</span>';
			}
		}
		return '';
		
	}
	/** 获取内容 */
	public static function getData($name, $mod = null){
		if($mod == null){
			$mod = basename(dirname($_SERVER['SCRIPT_FILENAME']));
		}
		$context = self::load($mod, null);
	
		if($context[$name] == null){
			trigger_error("未找到配置项，在{$mod}.cfg.php中！", E_USER_ERROR);
		}
		
		$retData = array();
		foreach($context[$name] as $cVal => &$cLabel){
			if(is_scalar($cLabel)){
				$retData[$cVal] = $cLabel;
			}
			if(is_array($cLabel)){
				$retData[$cLabel['val']] = $cLabel['label'];
			}
		}
		return $retData;
		
	}
}
